﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Net;
using System.Xml;
using DevDefined.OAuth.Consumer;
using DevDefined.OAuth.Framework;
using DevDefined.OAuth.Tests;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json.Linq;
using System.Web.Configuration;
using System.Configuration;
using MySql.Data.MySqlClient;
using Quartz;
using Quartz.Collection;
using Quartz.Impl;
using Quartz.Impl.Matchers;
using Quartz.Impl.Triggers;
using Quartz.Listener;
using Quartz.Simpl;
using Quartz.Spi;
using Quartz.Util;
using Quartz.Job;
using Quartz.Impl;
using Quartz.Impl.Calendar;
using Quartz.Impl.Matchers;
using C5;
using Common.Logging;


//using Quartz.Impl.JobDetail;
//using Quartz.JobExecutionContext;
//using Quartz.QuartzThread;
//using Quartz.TriggerUtils;
//using Quartz.CronExpression;

namespace WebApplication1
{
    public partial class Global : System.Web.HttpApplication
    {
        public static IScheduler _scheduler;

        INonceGenerator _nonceGenerator = new GuidNonceGenerator();

        public class GuidNonceGenerator : INonceGenerator
        {
            protected Random random = new Random();

            public string GenerateNonce(IOAuthConsumerContext context)
            {
                return Guid.NewGuid().ToString();
            }
        }

        public INonceGenerator NonceGenerator
        {
            get { return _nonceGenerator; }
            set { _nonceGenerator = value; }
        }



        public interface INonceGenerator
        {
            string GenerateNonce(IOAuthConsumerContext context);
        }


        IOAuthSession CreateMeshPlaceContext()
        {
            var consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = "2T_ImjIqp0_0SHSkn5_h9Q",
                SignatureMethod = SignatureMethod.HmacSha1,
                ConsumerSecret = "jLm7r2NgfKJj2oh00-LsrxCn1jg",
                Token = "FZ3d9I366L3JCr9_DSFILGj3gCOBSkgR",
                TokenSecret = "DjqExk9mS04RX88cbDoZL13rY4E"


            };

            consumerContext.Nonce = NonceGenerator.GenerateNonce(consumerContext);
            //consumerContext.NonceGenerator=

            return new OAuthSession(consumerContext)
                          .RequiresCallbackConfirmation();
        }


        public static void RequestPosts()
        {

            try
            {

                Global teste = new Global();
                
                IOAuthSession consumer = teste.CreateMeshPlaceContext();


                //Save to config file


                if (ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString() != "")
                {

                    MySqlConnection testCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
                    MySqlConnection testConTwo = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                    testCon.Open();
                    testConTwo.Open();

                    //Random random = new Random();
                    //int num = random.Next(1000);

                    string cmdTextZip = "SELECT * FROM Mesh_Zip";
                    MySqlCommand cmdZipCodes = new MySqlCommand(cmdTextZip, testCon);
                    MySqlDataReader theReader;
                    MySqlDataReader theReaderDataInZip;

                    theReader = cmdZipCodes.ExecuteReader();

                    List<string> theZipCodesList = new List<string>();

                    while (theReader.Read())
                    {

                        theZipCodesList.Add(theReader[0].ToString());


                    }

              //  SearchAgain:

                    string WhatZipCurrently;
                    string whatSearchTerm;

                    long j = 0;

                    while (j < theZipCodesList.Count)

                        j++;
                    //for (int j = 0; j < theZipCodesList.Count; j++)
                    {

                        WhatZipCurrently = ConfigurationManager.AppSettings["theZipCodeRow"].ToString();
                        whatSearchTerm = ConfigurationManager.AppSettings["Category"].ToString();


                        string theURL = "http://api.yelp.com/v2/search?term=" + whatSearchTerm + "&location=" + WhatZipCurrently;

                        string responseText = consumer.Request().Get().ForUrl(theURL).ToString();
                        JToken oToken = JObject.Parse(responseText);

                        JArray items = (JArray)oToken["businesses"];

                        JObject item;
                        JToken jUrl;
                        JToken jPostTitle;
                        JToken jPostImageURL;
                        JToken jSnippet;

                        
                        for (int i = 0; i < items.Count; i++)
                        {
                            item = (JObject)items[i];
                            jUrl = (string)item["url"];
                            jPostTitle = (string)item["name"];
                            jPostImageURL = (string)item["image_url"];
                            jSnippet = (string)item["snippet_text"];

                            string jTheTitle;
                            string theSnip;
                            string jTheImageurl;

                            try
                            {
                                jTheTitle = ((JValue)jPostTitle).Value.ToString().Replace("'", "''");
                            }
                            catch (Exception theExce)
                            {
                                jTheTitle = "";
                            }


                            try
                            {
                                theSnip = ((JValue)jSnippet).Value.ToString().Replace("'", "''");
                            }
                            catch (Exception theExce)
                            {
                                theSnip = "";
                            }

                            try
                            {
                                jTheImageurl = ((JValue)jPostImageURL).Value.ToString();
                            }
                            catch (Exception theExce)
                            {
                                jTheImageurl = "";
                            }

                            DateTime todaysDate = DateTime.Now;

                            string jTheDate = todaysDate.ToString("yyyy/MM/dd");

                            string cmdText = "INSERT INTO Mesh_Post (Post_Title ,Post_Date,Post_Link,Post_ImgURL,Post_Description,Post_Zip_Locale,UserNo,CategoryTitle) Values ('" + jTheTitle + "','" + jTheDate.ToString() + "','" + ((JValue)jUrl).Value.ToString() + "','" + jTheImageurl + "','" + theSnip + "','" + WhatZipCurrently + "',320,'Restaurants')";
                            MySqlCommand cmd = new MySqlCommand(cmdText, testConTwo);

                            cmd.ExecuteNonQuery();

                            if (i == items.Count - 1)
                            {
                                
                                Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
                                int theNewValue = Convert.ToInt32(config.AppSettings.Settings["ZipCodeCount"].Value) + 1;
                                config.AppSettings.Settings["ZipCodeCount"].Value = theNewValue.ToString();
                                config.AppSettings.Settings["theZipCodeRow"].Value = theZipCodesList[theNewValue].ToString();
                                config.Save(ConfigurationSaveMode.Modified);
                                ConfigurationManager.RefreshSection("appSettings");

                                //MySqlConnection testNP = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                                //testNP.Open();

                                //string InserNEwCM = "INSERT INTO Mesh_Post (Post_Title ,Post_Date,Post_Link,Post_ImgURL,Post_Description,Post_Zip_Locale,UserNo,CategoryTitle) Values ('" + j + "','date','url','imageurl','thenisp','78045',320,'Restaurants')";
                                //MySqlCommand cmdFinal = new MySqlCommand(InserNEwCM, testNP);

                                //cmdFinal.ExecuteNonQuery();
                                //testNP.Close();


                                //   goto SearchAgain;

                            }
                        }

                    }

                    testCon.Close();
                    testConTwo.Close();

                }


            }
            catch (Exception newExcept)
            {


               
            }



            //string name = (string)o["mobile_url"];
            //  }
            //catch (WebException webEx)
            //{
            //var response =responseText;
            ///    using (var reader = new StreamReader(response.GetResponseStream()))
            // {
            //      throw new Exception("WebException was thrown upon request, response content follows:\r\n\r\n" + reader.ReadToEnd(), webEx);
            //     }

            //}

        }

        protected void Application_Start(object sender, EventArgs e)
        {

            //try
            //{
           // Response.Write("<h2>Global Page Error</h2>\n");
                ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
                _scheduler = schedulerFactory.GetScheduler();
                _scheduler.Start();
                AddJob();
            
            //}
            //catch (Exception ex)
            //{

            //}
        }

        internal class MyJob : IJob 
        {
            public void Execute(IJobExecutionContext context)
            {

                MySqlConnection testNP = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                testNP.Open();

                string InserNEwCM = "INSERT INTO Mesh_Post (Post_Title ,Post_Date,Post_Link,Post_ImgURL,Post_Description,Post_Zip_Locale,UserNo,CategoryTitle) Values ('5','date','url','imageurl','thenisp','78045',320,'Restaurants')";
                MySqlCommand cmdFinal = new MySqlCommand(InserNEwCM, testNP);

                cmdFinal.ExecuteNonQuery();
                testNP.Close();

               // RequestPosts(); 
                //RequestPosts();

                // //const string zwsid = "X1-ZWz1dfzozk5amj_6jziz";
                //String url = "http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=X1-ZWz1dfzozk5amj_6jziz&citystatezip=78041";
                //HttpWebRequest Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);

                //string conString = "";

                //if (ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString() != "")
                //{

                //    MySqlConnection testCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                //    testCon.Open();

                //    Random random = new Random();
                //    int num = random.Next(1000);

                //    string cmdText = "INSERT INTO Mesh_Category (CategoryTitle ,CategoryDescription) Values ('" + num + "','CatDesc')";
                //    MySqlCommand cmd = new MySqlCommand(cmdText, testCon);
                //    cmd.ExecuteNonQuery();

                //    testCon.Close();

                //}
                
            }
        }

        public static void AddJob()
        {
            
            IJob myJob = new MyJob();
            JobDetailImpl jobDetail = new JobDetailImpl("Purge", "Group1", myJob.GetType());
            
            //  CronTriggerImpl trigger = new CronTriggerImpl("Trigger1", "Group1", "When to run it goes here");
            SimpleTriggerImpl trigger1 = new SimpleTriggerImpl("Trigger2", 950, TimeSpan.FromMinutes(1));
            _scheduler.ScheduleJob(jobDetail, trigger1);
            //    DateTimeOffset? nextFireTime = trigger.GetNextFireTimeUtc();
            //  Console.WriteLine("Next Fire Time:" + nextFireTime.Value);
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            //Response.Write("<h2>Global Page Error</h2>\n");
            //Response.Write(
            //    "<p>" + exc.Message + "</p>\n");
            //Response.Write("Return to the <a href='Default.aspx'>" +
            //    "Default Page</a>\n");
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
           // _scheduler.Interrupt("Purge");
            //_scheduler.Shutdown();
        }
    }
}